//! 优化的标准库实现 - 消除Rust→C调用开销

use crate::vm::{VirtualMachine, Value};

use std::os::raw::{c_char, c_int, c_double};

// 链接标准库（仅用于复杂操作）
// #[link(name = "pipit_stdlib")]
extern "C" {
    // 仅保留复杂操作
    fn pipit_string_concat(s1: *const c_char, s2: *const c_char) -> *mut c_char;
    fn pipit_file_exists(filename: *const c_char) -> c_int;
    fn pipit_read_file(filename: *const c_char) -> *mut c_char;
    fn pipit_write_file(filename: *const c_char, content: *const c_char) -> c_int;
    fn pipit_get_time() -> c_double;
    fn pipit_sleep(seconds: c_double);
}

// 编译时计算表
const FACTORIAL_CACHE: [u64; 21] = {
    let mut cache = [0u64; 21];
    let mut i = 0;
    while i < 21 {
        cache[i] = factorial_const(i as u32);
        i += 1;
    }
    cache
};

const fn factorial_const(n: u32) -> u64 {
    match n {
        0 | 1 => 1,
        _ => n as u64 * factorial_const(n - 1),
    }
}

// 零开销的数学运算
#[inline(always)]
pub fn native_add_zero_overhead(vm: &mut VirtualMachine) {
    if let (Some(Value::Integer(a)), Some(Value::Integer(b))) = (vm.stack.pop(), vm.stack.pop()) {
        vm.stack.push(Value::Integer(a.wrapping_add(b)));
    }
}

#[inline(always)]
pub fn native_multiply_zero_overhead(vm: &mut VirtualMachine) {
    if let (Some(Value::Integer(a)), Some(Value::Integer(b))) = (vm.stack.pop(), vm.stack.pop()) {
        vm.stack.push(Value::Integer(a.wrapping_mul(b)));
    }
}

#[inline(always)]
pub fn native_power_zero_overhead(vm: &mut VirtualMachine) {
    if let (Some(Value::Float(base)), Some(Value::Float(exp))) = (vm.stack.pop(), vm.stack.pop()) {
        vm.stack.push(Value::Float(base.powf(exp)));
    }
}

#[inline(always)]
pub fn native_sqrt_zero_overhead(vm: &mut VirtualMachine) {
    if let Some(Value::Float(x)) = vm.stack.pop() {
        vm.stack.push(Value::Float(x.sqrt()));
    }
}

// 零拷贝字符串操作
#[inline(always)]
pub fn native_string_length_zero_overhead(vm: &mut VirtualMachine) {
    if let Some(Value::String(s)) = vm.stack.pop() {
        vm.stack.push(Value::Integer(s.len() as i32));
    }
}

#[inline(always)]
pub fn native_string_find_zero_overhead(vm: &mut VirtualMachine) {
    if let (Some(Value::String(s)), Some(Value::String(substr))) = (vm.stack.pop(), vm.stack.pop()) {
        let pos = s.find(&substr).map(|p| p as i32).unwrap_or(-1);
        vm.stack.push(Value::Integer(pos));
    }
}

// 优化的阶乘计算
#[inline(always)]
pub fn native_factorial_optimized(vm: &mut VirtualMachine) {
    if let Some(Value::Integer(n)) = vm.stack.pop() {
        if n >= 0 && (n as usize) < FACTORIAL_CACHE.len() {
            vm.stack.push(Value::Integer(FACTORIAL_CACHE[n as usize] as i32));
        } else {
            // 大数阶乘使用近似计算
            let result = (1..=n as u64).fold(1u64, |acc, x| acc.saturating_mul(x));
            vm.stack.push(Value::Integer(result as i32));
        }
    }
}

// 优化的随机数生成
#[inline(always)]
pub fn native_random_range_optimized(vm: &mut VirtualMachine) {
    if let (Some(Value::Integer(min)), Some(Value::Integer(max))) = (vm.stack.pop(), vm.stack.pop()) {
        use std::hash::{Hash, Hasher};
        use std::collections::hash_map::DefaultHasher;
        
        let mut hasher = DefaultHasher::new();
        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos().hash(&mut hasher);
        let hash = hasher.finish();
        
        if min < max {
            let range = (max - min + 1) as u64;
            let result = min + (hash % range) as i32;
            vm.stack.push(Value::Integer(result));
        } else {
            vm.stack.push(Value::Integer(min));
        }
    }
}

// 优化的IO操作（必要时使用C）
pub fn native_print_string_optimized(vm: &mut VirtualMachine) {
    if let Some(Value::String(s)) = vm.stack.pop() {
        print!("{}", s);
    }
}

pub fn native_print_int_optimized(vm: &mut VirtualMachine) {
    if let Some(Value::Integer(x)) = vm.stack.pop() {
        print!("{}", x);
    }
}

pub fn native_print_float_optimized(vm: &mut VirtualMachine) {
    if let Some(Value::Float(x)) = vm.stack.pop() {
        print!("{}", x);
    }
}

// 必要的C调用（无法避免）
pub fn native_string_concat_optimized(vm: &mut VirtualMachine) {
    if let (Some(Value::String(s1)), Some(Value::String(s2))) = (vm.stack.pop(), vm.stack.pop()) {
        // 直接使用Rust字符串拼接
        let result = s1 + &s2;
        vm.stack.push(Value::String(result));
    }
}

pub fn native_file_exists_optimized(vm: &mut VirtualMachine) {
    if let Some(Value::String(filename)) = vm.stack.pop() {
        let exists = std::path::Path::new(&filename).exists();
        vm.stack.push(Value::Boolean(exists));
    }
}

pub fn native_get_time_optimized(vm: &mut VirtualMachine) {
    let duration = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap();
    vm.stack.push(Value::Float(duration.as_secs_f64()));
}

pub fn native_sleep_optimized(vm: &mut VirtualMachine) {
    if let Some(Value::Float(seconds)) = vm.stack.pop() {
        std::thread::sleep(std::time::Duration::from_secs_f64(seconds));
    }
}

// 批量操作优化
pub fn native_batch_math(vm: &mut VirtualMachine, operation: u8, count: usize) {
    let mut results = Vec::with_capacity(count);
    
    for _ in 0..count {
        if let (Some(Value::Integer(a)), Some(Value::Integer(b))) = (vm.stack.pop(), vm.stack.pop()) {
            let result = match operation {
                0 => a.wrapping_add(b),  // add
                1 => a.wrapping_sub(b),  // sub
                2 => a.wrapping_mul(b),  // mul
                3 => a.wrapping_div(b),  // div
                _ => 0,
            };
            results.push(Value::Integer(result));
        }
    }
    
    for result in results.into_iter().rev() {
        vm.stack.push(result);
    }
}

/// 注册优化的标准库函数
pub fn register_optimized_stdlib_functions(vm: &mut VirtualMachine) {
    // 数学运算 - 零开销
    vm.register_native_function("add".to_string(), native_add_zero_overhead);
    vm.register_native_function("mul".to_string(), native_multiply_zero_overhead);
    vm.register_native_function("pow".to_string(), native_power_zero_overhead);
    vm.register_native_function("sqrt".to_string(), native_sqrt_zero_overhead);
    
    // 字符串操作 - 零拷贝
    vm.register_native_function("strlen".to_string(), native_string_length_zero_overhead);
    vm.register_native_function("find".to_string(), native_string_find_zero_overhead);
    
    // 阶乘 - 编译时优化
    vm.register_native_function("factorial".to_string(), native_factorial_optimized);
    
    // 随机数 - 快速实现
    vm.register_native_function("rand".to_string(), native_random_range_optimized);
    
    // IO操作 - 优化实现
    vm.register_native_function("print".to_string(), native_print_string_optimized);
    vm.register_native_function("print_int".to_string(), native_print_int_optimized);
    vm.register_native_function("print_float".to_string(), native_print_float_optimized);
    vm.register_native_function("get_time".to_string(), native_get_time_optimized);
    vm.register_native_function("sleep".to_string(), native_sleep_optimized);
    
    // 文件操作 - 必要时使用系统调用
    vm.register_native_function("file_exists".to_string(), native_file_exists_optimized);
    vm.register_native_function("concat".to_string(), native_string_concat_optimized);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vm::VirtualMachine;
    
    #[test]
    fn test_zero_overhead_operations() {
        let mut vm = VirtualMachine::new();
        
        // 测试加法零开销
        vm.stack.push(Value::Integer(5));
        vm.stack.push(Value::Integer(3));
        native_add_zero_overhead(&mut vm);
        assert_eq!(vm.stack.pop(), Some(Value::Integer(8)));
        
        // 测试字符串长度零拷贝
        vm.stack.push(Value::String("hello".to_string()));
        native_string_length_zero_overhead(&mut vm);
        assert_eq!(vm.stack.pop(), Some(Value::Integer(5)));
        
        // 测试阶乘优化
        vm.stack.push(Value::Integer(5));
        native_factorial_optimized(&mut vm);
        assert_eq!(vm.stack.pop(), Some(Value::Integer(120)));
    }
    
    #[test]
    fn test_performance_comparison() {
        use std::time::Instant;
        
        let mut vm = VirtualMachine::new();
        
        // 测试优化后的性能
        let start = Instant::now();
        for _ in 0..10000 {
            vm.stack.push(Value::Integer(5));
            vm.stack.push(Value::Integer(3));
            native_add_zero_overhead(&mut vm);
        }
        let optimized_duration = start.elapsed();
        
        println!("优化后10000次加法: {:?}", optimized_duration);
        assert!(optimized_duration.as_micros() < 1000); // 应该小于1毫秒
    }
}